import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { formatDate } from 'utils';
import { ConfigurationService } from '../configuration/configuration.service';

@Injectable()
export class EmailService {
  constructor(
    private readonly mailService: MailerService,
    private readonly configurationService: ConfigurationService
  ) { }

  /**
   * 发送邮件
   * @param body 邮件内容数据
   * @returns 发送结果
   */
  async sendEmail(body: any) {
    try {
      // 获取活跃的邮件配置
      const emailConfig = await this.configurationService.getActiveEmailConfig();

      // 构建邮件选项
      const mailOptions: ISendMailOptions = {
        to: {
          name: emailConfig.emailToName || '本机',
          address: emailConfig.emailToAddress || '2735332396@qq.com',
        },
        subject: body.productionName ? '询问产品' : '客户留言',
        html: body.content,
      };

      // 如果配置了发件人信息，使用配置的信息
      if (emailConfig && emailConfig.emailUser) {
        mailOptions.from = {
          name: emailConfig.emailName,
          address: emailConfig.emailUser,
        };
      } else {
        // 使用默认发件人信息
        mailOptions.from = {
          name: '客户留言-Awesome',
          address: '2735332396@qq.com',
        };
      }

      const res = await this.mailService.sendMail(mailOptions);
      return res.response;
    } catch (e) {
      console.error('发送邮件失败:', e);
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST);
      } else {
        throw new HttpException(
          '服务器内部错误',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

  /**
   * 获取当前邮件配置信息
   * @returns 邮件配置信息
   */
  async getEmailConfig() {
    try {
      const emailConfig = await this.configurationService.getActiveEmailConfig();

      if (emailConfig) {
        return {
          host: emailConfig.emailHost || 'smtp.qq.com',
          port: emailConfig.emailPort || 587,
          secure: emailConfig.emailSecure || false,
          user: emailConfig.emailUser || '2735332396@qq.com',
          fromName: '客户留言系统',
          fromAddress: emailConfig.emailUser || '2735332396@qq.com'
        };
      }

      // 返回默认配置
      return {
        host: 'smtp.qq.com',
        port: 587,
        secure: false,
        user: '2735332396@qq.com',
        fromName: '客户留言系统',
        fromAddress: '2735332396@qq.com'
      };
    } catch (error) {
      console.error('获取邮件配置失败:', error);
      throw new HttpException(
        '获取邮件配置失败',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}
